package cn.bellychang.deferredresult;

import cn.bellychang.model.ORDER_STATUS_ENUM;
import cn.bellychang.model.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author ChangLiang
 * @date 2020/9/23
 */
@Component
public class MockQueue {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());

    private BlockingQueue<Order> queue;

    public MockQueue() {
        queue = new LinkedBlockingQueue<>();
    }

    public BlockingQueue getQueue() {
        return queue;
    }

    public void receiveOrder(Order order) {
        new Thread(()->{
            LOGGER.info("接到下单请求，order: {}", order);
            // mock process
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            order.setStatus(ORDER_STATUS_ENUM.completed.name());
            try {
                queue.put(order);
            } catch (InterruptedException e) {
                order.setStatus(ORDER_STATUS_ENUM.error.name());
                e.printStackTrace();
            }
            LOGGER.info("下单请求处理完毕, order:{}", order);
        },"application2:order-process-thread").start();
    }
}
